package com.atguigu.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.ArrayList;
import java.util.Properties;

/**
 * @author code1997
 */
public class InterceptorProducer {
    public static void main(String[] args) {
        //1 创建kafka生产者的配置信息
        Properties properties = new Properties();
        //2 指定链接的kafka集群
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop02:9092");
        //3 ack的应答级别
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        //4 重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 1);
        //5 批次大小
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        //6 等待时间
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        //7 RecordAccumulator 缓冲区大小(32M)
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        //8 k,v序列化的类
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                StringSerializer.class);
        //添加拦截器链
        ArrayList<String> interceptors = new ArrayList<>();
        interceptors.add("com.atguigu.interceptor.TimeInterceptor");
        interceptors.add("com.atguigu.interceptor.CountInterceptor");
        properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, interceptors);
        //9 创建生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        //10 发送数据
        for (int i = 0; i < 10; i++) {

            producer.send(new ProducerRecord<>("kafka-test", "code1997", "code1997_" + i));
        }
        //11 关闭资源:会执行一些操作，比如清空内存中的数据。
        try {
            //防止执行时间太短，batch.size没满并且等待时间都没到，主线程就结束了
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //不光将生产者的消息关闭，拦截器之类的资源也会进行关闭。如果不关闭的情况下，有可能消息不会被发送：
        producer.close();
    }
}
